'use strict';

/**
 * app.directives
 */
angular.module('app.directives', ['ui.load'])
  .directive('uiModule', ['MODULE_CONFIG', 'uiLoad', '$compile', function (MODULE_CONFIG, uiLoad, $compile) {
    return {
      restrict: 'A',
      compile: function (el, attrs) {
        var contents = el.contents().clone();
        return function (scope, el, attrs) {
          el.contents().remove();
          uiLoad.load(MODULE_CONFIG[attrs.uiModule])
            .then(function () {
              $compile(contents)(scope, function (clonedElement, scope) {
                el.append(clonedElement);
              });
            });
        }
      }
    };
  }])
  .directive('uiShift', ['$timeout', function ($timeout) {
    return {
      restrict: 'A',
      link: function (scope, el, attr) {
        // get the $prev or $parent of this el
        var _el = $(el),
          _window = $(window),
          prev = _el.prev(),
          parent,
          width = _window.width()
          ;

        !prev.length && (parent = _el.parent());

        function sm() {
          $timeout(function () {
            var method = attr.uiShift;
            var target = attr.target;
            _el.hasClass('in') || _el[method](target).addClass('in');
          });
        }

        function md() {
          parent && parent['prepend'](el);
          !parent && _el['insertAfter'](prev);
          _el.removeClass('in');
        }

        (width < 768 && sm()) || md();

        _window.resize(function () {
          if (width !== _window.width()) {
            $timeout(function () {
              (_window.width() < 768 && sm()) || md();
              width = _window.width();
            });
          }
        });
      }
    };
  }])
  .directive('uiToggleClass', ['$timeout', '$document', function ($timeout, $document) {
    return {
      restrict: 'AC',
      link: function (scope, el, attr) {
        el.on('click', function (e) {
          e.preventDefault();
          var classes = attr.uiToggleClass.split(','),
            targets = (attr.target && attr.target.split(',')) || Array(el),
            key = 0;
          angular.forEach(classes, function (_class) {
            var target = targets[(targets.length && key)];
            (_class.indexOf('*') !== -1) && magic(_class, target);
            $(target).toggleClass(_class);
            key++;
          });
          $(el).toggleClass('active');

          function magic(_class, target) {
            var patt = new RegExp('\\s' +
              _class.
                replace(/\*/g, '[A-Za-z0-9-_]+').
                split(' ').
                join('\\s|\\s') +
              '\\s', 'g');
            var cn = ' ' + $(target)[0].className + ' ';
            while (patt.test(cn)) {
              cn = cn.replace(patt, ' ');
            }
            $(target)[0].className = $.trim(cn);
          }
        });
      }
    };
  }])
  .directive('uiNav', ['$timeout', function ($timeout) {
    return {
      restrict: 'AC',
      link: function (scope, el, attr) {
        var _window = $(window),
          _mb = 768,
          wrap = $('.app-aside'),
          next,
          backdrop = '.dropdown-backdrop';
        // unfolded
        el.on('click', 'a', function (e) {
          next && next.trigger('mouseleave.nav');
          var _this = $(this);
          _this.parent().siblings(".active").toggleClass('active');
          _this.next().is('ul') && _this.parent().toggleClass('active') && e.preventDefault();
          // mobile
          _this.next().is('ul') || ((_window.width() < _mb) && $('.app-aside').removeClass('show off-screen'));
        });

        // folded & fixed        
        el.on('mouseenter', 'a', function (e) {
          next && next.trigger('mouseleave.nav');
          $('> .nav', wrap).remove();
          if (!$('.app-aside-fixed.app-aside-folded').length || (_window.width() < _mb)) return;
          var _this = $(e.target)
            , top
            , w_h = $(window).height()
            , offset = 50
            , min = 150;

          !_this.is('a') && (_this = _this.closest('a'));
          if (_this.next().is('ul')) {
            next = _this.next();
          } else {
            return;
          }

          _this.parent().addClass('active');
          top = _this.parent().position().top + offset;
          next.css('top', top);
          if (top + next.height() > w_h) {
            next.css('bottom', 0);
          }
          if (top + min > w_h) {
            next.css('bottom', w_h - top - offset).css('top', 'auto');
          }
          next.appendTo(wrap);

          next.on('mouseleave.nav', function (e) {
            $(backdrop).remove();
            next.appendTo(_this.parent());
            next.off('mouseleave.nav').css('top', 'auto').css('bottom', 'auto');
            _this.parent().removeClass('active');
          });

          $('.smart').length && $('<div class="dropdown-backdrop"/>').insertAfter('.app-aside').on('click', function (next) {
            next && next.trigger('mouseleave.nav');
          });

        });

        wrap.on('mouseleave', function (e) {
          next && next.trigger('mouseleave.nav');
          $('> .nav', wrap).remove();
        });
      }
    };
  }])
  .directive('uiScroll', ['$location', '$anchorScroll', function ($location, $anchorScroll) {
    return {
      restrict: 'AC',
      link: function (scope, el, attr) {
        el.on('click', function (e) {
          $location.hash(attr.uiScroll);
          $anchorScroll();
        });
      }
    };
  }])
  .directive('uiFullscreen', ['uiLoad', function (uiLoad) {
    return {
      restrict: 'AC',
      template: '<i class="fa fa-expand fa-fw text"></i><i class="fa fa-compress fa-fw text-active"></i>',
      link: function (scope, el, attr) {
        el.addClass('hide');
        uiLoad.load('js/libs/screenfull.min.js').then(function () {
          if (screenfull.enabled) {
            el.removeClass('hide');
          }
          el.on('click', function () {
            var target;
            attr.target && (target = $(attr.target)[0]);
            el.toggleClass('active');
            screenfull.toggle(target);
          });
        });
      }
    };
  }])
  .directive('uiButterbar', ['$rootScope', '$anchorScroll', function ($rootScope, $anchorScroll) {
    return {
      restrict: 'AC',
      template: '<span class="bar"></span>',
      link: function (scope, el, attrs) {
        el.addClass('butterbar hide');
        scope.$on('$stateChangeStart', function (event) {
          $anchorScroll();
          el.removeClass('hide').addClass('active');
        });
        scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
          event.targetScope.$watch('$viewContentLoaded', function () {
            el.addClass('hide').removeClass('active');
          })
        });
      }
    };
  }])
  .directive('setNgAnimate', ['$animate', function ($animate) {
    return {
      link: function ($scope, $element, $attrs) {
        $scope.$watch(function () {
          return $scope.$eval($attrs.setNgAnimate, $scope);
        }, function (valnew, valold) {
          $animate.enabled(!!valnew, $element);
        });
      }
    };
  }])
   /*
     * Usage: ng-compile='htmlGotFromServer'
     */
    .directive('ngCompile', [
        '$compile',
        function ($compile) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    scope.$watch(
                        function (scope) {
                            // watch the 'compile' expression for changes
                            return scope.$eval(attrs.ngCompile);
                        },
                        function (value) {
                            // when the 'compile' expression changes
                            // assign it into the current DOM
                            element.html(value);
                            if (angular.isDefined(value) === false || value === '') return;
                            // compile the new DOM and link it to the current
                            // scope.
                            // NOTE: we only compile .childNodes so that
                            // we don't get into infinite loop compiling ourselves
                            $compile(element.contents())(scope);
                        }
                    );
                }
            };
        }
    ])
    /**
     * Bind file from input to model
     * Usage:<input type=file ng-file-model='a model in $scope' target='id to trigger this input' />
     */
    .directive('ngFileModel', [
        function () {
            return {
                scope: {
                    ngFileModel: '='
                },
                link: function (scope, element, attrs) {
                    if(attrs['target']){
                        var target=document.getElementById(attrs['target']);
                        if(target){
                            target.addEventListener('click',function(event){
                                event.preventDefault();
                                event.stopPropagation();
                                element[0].click();
                            });
                            if(attrs['selfHidden']) element[0].style.display='none';
                        }
                    }
                    element.bind('change', chooseFile);
                    
                    function chooseFile (changeEvent) {
                        var file = changeEvent.target.files[0];
                        var reader = new FileReader();
                        reader.onload = function (loadEvent) {
                            scope.$apply(function () {
                                scope.ngFileModel = {
                                    file: file,
                                    model: {
                                        lastModified: changeEvent.target.files[0].lastModified,
                                        lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
                                        name: changeEvent.target.files[0].name,
                                        size: changeEvent.target.files[0].size,
                                        type: changeEvent.target.files[0].type,
                                        data: loadEvent.target.result
                                    }
                                };
                                scope.ngFileModel.model.ext = scope.ngFileModel.model.name.substring(scope.ngFileModel.model.name.lastIndexOf('.'));
                            });
                        }
                        reader.readAsDataURL(changeEvent.target.files[0]);
                    }
                }
            }
        }
    ])
/**
     * A generic confirmation for risky actions.
     * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
     */
    .directive('ngReallyClick', [
        function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.bind('click', function () {
                        var message = attrs.ngReallyMessage;
                        if (message && confirm(message)) {
                            scope.$apply(attrs.ngReallyClick);
                        }
                    });
                }
            }
        }
    ])

    .directive('fixTo',[
        function(){
            return function(scope,element,attrs){
                var fixTo=$(attrs.fixTo);
                var fixOffset=fixTo.offset();
                element.css({
                    'position':'fixed',
                    'top':(fixOffset.top+fixTo.height()+50)+'px',
                    'left':(fixOffset.left+fixTo.width())+'px'
                });
            }
        }
    ])
  ;



/**
 * app.filters
 */
angular.module('app.filters', [])
  .filter('fromNow', function () {
    return function (date) {
      return moment(date).fromNow();
    }
  })
  ;


/**
 * app.services
 */

angular.module('app.services', ['ngCookies','base64'])
    .factory('oauthService', [
        '$http', '$q', '$cookies', '$base64','APP_CONFIG',
        function($http, $q, $cookies, $base64,APP_CONFIG) {
            var oauth = {
                access_token: '',
                token_type: '',
                expiresAt: 0
            };
            var clientId = 'fghaeth0934u51tjuydxzs38y289836';
            var clientSecret = '673fd777898013849760f56nmoidfnyi7je';

            var service = {};

            /*
            * current time, unit: ms
            */
            function getTime() {
                return new Date().getTime();
            }

            /*
            * generate Basic Authentication header
            */
            function getBasicAuthentication() {
                var headerValue = 'Basic ' + $base64.encode(clientId + ':' + clientSecret);
                return {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': headerValue
                };
            }

            /*
            * form url and endcode
            */
            function formUrlEncode(obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                return str.join('&');
            }


            // load from cookie
            oauth=$cookies.getObject(APP_CONFIG.tokenCookieKey)||{};
            /*
                * return token if it's valid, otherwise return empty string
                */
            service.getToken = function() {
                if (angular.isDefined(oauth) && oauth.expiresAt > getTime()) {
                    return oauth.token_type + ' ' + oauth.access_token;
                }
                console.log('access token is expired or not exist');
                return '';
            };
            /*
             * basic token of client
             */
            service.getBasicToken = function() {
                var defer = $q.defer();
                if (service.getToken() === '') {
                    service.clear();
                    var clientTokenConfig = {
                        method: 'POST',
                        url: '/token',
                        headers: getBasicAuthentication(),
                        transformRequest: formUrlEncode,
                        data: { grant_type: 'client_credentials' }
                    };
                    $http(clientTokenConfig)
                        .success(function(result) {
                            oauth.access_token = result.access_token;
                            oauth.token_type = result.token_type === 'basic' ? 'Basic' : result.token_type === 'bearer' ? 'Bearer' : result.token_type;
                            oauth.expiresAt = getTime() + result.expires_in * 1e3;
                            $cookies.putObject(APP_CONFIG.tokenCookieKey,oauth);
                            defer.resolve({ success: true });
                        })
                        .error(function(err) {
                            console.log('get client token failed.');
                            console.log(err);
                            defer.resolve({success:false,error:err});
                        });
                } else {
                    defer.resolve({ success: true });
                }
                return defer.promise;
            };

            /*
                * get user's token when logining
                */
            service.tryLogin = function(userName, password) {
                var defer = $q.defer();
                var clientTokenConfig = {
                    method: 'POST',
                    url: '/token',
                    headers: getBasicAuthentication(),
                    transformRequest: formUrlEncode,
                    data: {
                        'grant_type': 'password',
                        'username': userName,
                        'password': password
                    }
                };
                $http(clientTokenConfig)
                    .success(function(result) {
                        oauth.access_token = result.access_token;
                        oauth.token_type = result.token_type === 'basic' ? 'Basic' : result.token_type === 'bearer' ? 'Bearer' : result.token_type;
                        oauth.expiresAt = getTime() + result.expires_in * 1e3;
                        $cookies.putObject(APP_CONFIG.tokenCookieKey,oauth);
                        defer.resolve({ success: true });
                    })
                    .error(function(err) {
                        defer.resolve({ success: false, error: err.error_description || '用户名或者密码错误' });
                        console.log('request client token failed.');
                        console.log(err);
                    });
                return defer.promise;
            };

            /*
             * test if user is logined
             */
            service.testLogin = function() {
                var defer = $q.defer();
                if (service.getToken() === '') {
                    defer.resolve({ success: false, code: -1 });
                } else if (oauth.isLogin === true) {
                    defer.resolve({ success: true });
                    return defer.promise;
                } else {
                    $http.get('/api/account/AuthStatus')
                        .then(function(result) {
                                if (result.status === 200) {
                                    defer.resolve({ success: true });
                                    oauth.isLogin = true;
                                } else {
                                    defer.resolve({ success: false, code: -2 });
                                }
                            },
                            function(x) {
                                defer.resolve({ success: false, code: -3 });
                                console.log('request auth status failed');
                                console.log(x);
                            });
                }
                return defer.promise;
            };
            /*
             * clear the authorization
             */
            service.clear = function() {
                 oauth = {};
                 $cookies.remove(APP_CONFIG.tokenCookieKey);
            }
            return service;
        }
    ])
    .factory('appInterceptor',[
        '$rootScope', '$q', '$cookies','APP_CONFIG',
      function ($rootScope, $q, $cookies, APP_CONFIG) {
        var isLogin = true;
        var extsOfStaticRequest = ['.html', '.htm', '.css', '.js', '.jpg', '.png', '.gif', '.eot', '.svg', '.ttf', '.woff', '.otf','.json'];

        function getExt(url) {
            return url.substring(url.lastIndexOf('.'));
        }

        function startWith(str, start) {
            return str.substring(0, start.length) === start;
        }

        function isAbsolute(url) {
            return startWith(url, 'http://') || startWith(url, 'https://');
        }

        function getTime(time) {
            return (time || new Date()).getTime();
        }

        /**
         * 将Api请求指向Api服务器Host
         * @param {} config 
         * @returns {} 
         */
        function isApiRequest(config) {
            var isApi = false;
            if (!isAbsolute(config.url)) {
                //相对地址
                if (config.method.toLowerCase() === 'post') {
                    //post
                    isApi = true;
                } else {
                    var ext = getExt(config.url);
                    if (extsOfStaticRequest.indexOf(ext) < 0) {
                        //非静态资源
                        isApi = true;
                    }
                }
            }
            if (isApi) {
                config.url = APP_CONFIG.apiHost + config.url;
            }
            return isApi;
        }


        var oauth = undefined;

        function getToken() {
            oauth = oauth || $cookies.getObject(APP_CONFIG.tokenCookieKey);
            if (angular.isDefined(oauth) && oauth.expiresAt > getTime()) {
                return oauth.token_type + ' ' + oauth.access_token;
            }
            return '';
        }

        function sayNotLogin() {
            if (isLogin) {
                isLogin = false;
                $rootScope.$emit(APP_CONFIG.eventUserNotLogin, 'notLogin');
            }
        }
        
        return {
            request: function(config) {
                //add authorization header except token request
                if (isApiRequest(config)) {
                    if (angular.isDefined(config.headers.Authorization) === false) {
                        var token = getToken();
                        if (token === '') {
                            sayNotLogin();
                            return $q.reject(config);
                        }
                        config.headers.Authorization = token;
                    }
                }
                $rootScope.delayLoading++;
                return config;
            },
            response: function(response) {
                $rootScope.delayLoading--;
                //!isLogin && (isLogin = true);
                return response;
            },
            responseError: function(response) {
                $rootScope.delayLoading--;
                $rootScope.$emit(APP_CONFIG.eventHttpError, response.status);
                return $q.reject(response);
            }
        };
    }
    ])
    .factory('alertService',[
        '$rootScope','$modal',
       function ($rootScope, $modal) {
           var service = {};
           service.add = function (msg, type, timeout) {
               if ($rootScope.modalInstance) {
                   $rootScope.modalInstance.dismiss();
               }
               type = type || 'error';
               timeout = timeout || 10;
               msg = msg || '操作失败，请稍后再试';
               $rootScope.modalInstance = $modal.open({
                   template: '<div class="modal-header"><p class="modal-title">提示</p></div>'
                       + '<div class="modal-body"><p><i class="fa ' + (type === 'success' ? 'fa-check-circle text-success' : type === 'error' ? 'fa-times-circle text-danger' : 'fa-info-circle') + '"></i> ' + msg + '</p></div>'
                       + '<div class="modal-footer"><p><small>{{tick}}秒后自动关闭</small><button class="btn btn-primary btn-ok" ng-click="closeAlert($event)">确定</button><p><div>',
                   windowClass: 'alert-modal',
                   backdrop: true,
                   controller: ['$scope', '$interval', function ($scope, $interval) {
                       $scope.tick = timeout;
                       var timer = $interval(function () {
                           $scope.tick > 0 && ($scope.tick--);
                           if ($scope.tick <= 0) {
                               $interval.cancel(timer);
                               timer = undefined;
                               $rootScope.modalInstance.dismiss('timeout');
                           }
                       }, 1e3);
                       //close alert
                       $scope.closeAlert = function ($event) {
                           $rootScope.modalInstance.dismiss($event);
                       };
                       $scope.$on('$destroy', function () {
                           if (timer) {
                               $interval.cancel(timer);
                               timer = undefined;
                           }
                       });
                   }]
               });
           };

           service.error = function(msg, err) {
               service.add(msg,'error');
               err && console.error(err);
           };

           service.success = function (msg) {
               service.add(msg, 'success');
           };
           return service;
        }
    ])
    .factory('accountService',[
        '$http', '$q', '$cookies',
        function ($http, $q, $cookies) {
            var service = {};
            /*
             * request user's profile
             */
            service.getUserData = function () {
                var defer = $q.defer();
                service.getLocalUserData();
                if (angular.isDefined(service.user)) {
                    defer.resolve({ success: true, user: service.user });
                } else {
                    $http.get('/api/account/userInfo')
                        .success(function(result) {
                            if (result.Code >= 0) {
                                service.user = result.Data;
                                $cookies.putObject('oauthuser', service.user);
                                defer.resolve({ success: true, user: service.user });
                            } else {
                                defer.resolve({ success: false, error: result.Message });
                            }
                        })
                        .error(function(x) {
                            defer.reject({ success: false, error: '查询用户信息失败' });
                            console.log('request user\'s data failed');
                            console.log(x);
                        });
                }
                return defer.promise;
            }
            /*
             * local user data saved in cookie when logined
             */
            service.getLocalUserData = function () {
                if (angular.isDefined(service.user)) {
                    return service.user;
                }
                return service.user = $cookies.getObject('oauthuser');
            };


            service.isInRole = function (roles) {
                var user = service.getLocalUserData();
                if (!angular.isDefined(user)) return false;
                if (user.Roles.indexOf('系统管理员') >= 0) return true;
                if (angular.isArray(roles) === false) {
                    roles = [roles];
                }
                for (var i = 0; i < roles.length; i++) {
                    if (user.Roles.indexOf(roles[i]) >= 0) return true;
                }
                return false;
            };
            
            service.logout = function() {
                service.user = undefined;
            };
            
              service.updateUser = function (newData) {
                angular.extend(service.user, newData);
                $cookies.putObject('oauthuser', service.user);
            };

            return service;
        }
    ])

    .factory('fileService', [
        '$http', '$q',
        function($http, $q) {
            var self = {};

            self.upload = function (file) {
                var defer = $q.defer();
                if (!angular.isDefined(file)) {
                    defer.resolve();
                    return defer.promise;
                }
                var fileHttpConfig = {
                    headers: {
                        'Content-Type': undefined
                    },
                    method: 'POST',
                    url: '/File/Upload',
                    data: { '': file },
                    transformRequest: function (data, headersGetter) {
                        var formData = new FormData();
                        angular.forEach(data, function (value, key) {
                            formData.append(key, value);
                        });
                        var headers = headersGetter();
                        delete headers['Content-Type'];
                        return formData;
                    }
                };

                $http(fileHttpConfig)
                    .success(function (result) {
                        if (result.Code >= 0) {
                            defer.resolve(result.Message);
                        } else {
                            defer.reject(result.Message);
                        }
                    })
                    .error(function (x) {
                        defer.reject('上传文件失败');
                    });
                return defer.promise;
            }

            return self;
        }
    ])
;

/**
 * app.controllers
 */
angular.module('app.controllers', ['pascalprecht.translate', 'ngCookies'])
  .controller('AppCtrl', [
    '$rootScope', '$scope', '$localStorage', '$window', '$state','$timeout','$translate', 'alertService', 'oauthService', 'accountService','APP_CONFIG',
        function($rootScope, $scope, $localStorage, $window, $state, $timeout,$translate,alertService, oauthService, accountService,APP_CONFIG) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice($window) && angular.element($window.document.body).addClass('smart');

      // config
      $scope.app = {
        name: '深圳市南山区文化馆',
        shortName: '南山文化',
        version: '1.0.0',
        // for chart colors
        color: {
          primary: '#7266ba',
          info: '#23b7e5',
          success: '#27c24c',
          warning: '#fad733',
          danger: '#f05050',
          light: '#e8eff0',
          dark: '#3a3f51',
          black: '#1c2b36'
        },
        settings: {
          themeID: 1,
          navbarHeaderColor: 'bg-black',
          navbarCollapseColor: 'bg-white-only',
          asideColor: 'bg-black',
          headerFixed: true,
          asideFixed: false,
          asideFolded: false
        }
      }
      // save settings to local storage
      if (angular.isDefined($localStorage.settings)) {
        $scope.app.settings = $localStorage.settings;
      } else {
        $localStorage.settings = $scope.app.settings;
      }
      $scope.$watch('app.settings', function () { $localStorage.settings = $scope.app.settings; }, true);

      // angular translate
      $scope.lang = { isopen: false };
      $scope.langs = { zh_CN: '中文' };
      $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "zh_CN";
      $scope.setLang = function (langKey, $event) {
        // set the current lang
        $scope.selectLang = $scope.langs[langKey];
        // You can change the language during runtime
        $translate.use(langKey);
        $scope.lang.isopen = !$scope.lang.isopen;
      };

      function isSmartDevice($window) {
        // Adapted from http://www.detectmobilebrowsers.com
        var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
        // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
        return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
      }
      $rootScope.delayLoading = 0;
      $rootScope.$watch("delayLoading", function (newVal) {
        if (newVal > 0) {
          $timeout(function () {
            if ($rootScope.delayLoading > 0) {
              ! $rootScope.loading && ( $rootScope.loading = true);
            }
          }, 100);
        } else {
           $rootScope.loading && ( $rootScope.loading = false);
        }
      });


      function getLocalUserData() {
        $scope.user = accountService.getLocalUserData();
      }

      getLocalUserData();
      //页面跳转状态
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

      });
      $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        if ($rootScope.modalInstance) {
          $rootScope.modalInstance.dismiss();
        }
      });
      //用户未登录
      $rootScope.$on(APP_CONFIG.eventUserNotLogin, function () {
        $state.go('access.signin');
      });
      //获取用户信息
      $rootScope.$on(APP_CONFIG.eventUserLoaded, function (user) {
        getLocalUserData();
      });

      //http请求异常
      $rootScope.$on(APP_CONFIG.eventHttpError, function (event, error) {
        switch (error) {
          case 401:
            $state.go('login');
            break;
          case 400:
          case 403:
          case 404:
          case 408:
          //timeout
          default:
            break;
        }
      });
    }
  ]);